package com.zj.utils.map;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.zj.utils.utils.utilcode.ToastUtils;

import org.osmdroid.tileprovider.modules.ArchiveFileFactory;
import org.osmdroid.tileprovider.modules.IArchiveFile;
import org.osmdroid.tileprovider.modules.OfflineTileProvider;
import org.osmdroid.tileprovider.tilesource.FileBasedTileSource;
import org.osmdroid.tileprovider.tilesource.OnlineTileSourceBase;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.tileprovider.tilesource.XYTileSource;
import org.osmdroid.tileprovider.util.SimpleRegisterReceiver;
import org.osmdroid.util.MapTileIndex;
import org.osmdroid.views.MapView;

import java.io.File;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * 谷歌、高德、天地图等瓦片地图
 *
 * @author jiang zhu on 2019/10/18
 */
public class GoogleTileSource extends TileSourceFactory {
    //http://mt0.google.cn/vt/lyrs=y@883&hl=zh-CN&gl=cn&src=app&x=216483&y=100141&z=18&s=Galileo
    //下方给出各种图源的数据，在添加图源时要用上以下数据: [谷歌卫星图] 名称: 谷歌卫星
    //图描述:瓦片大小: 512最小级别: 1最大级别: 19坐标偏移: GCJ (不要弄错) 安卓端
    //瓦片下载地址: htp://mt{$s}.google.cntlyrs=y&hl=zh-CN&gI=cn&scale=2&x={$x}&y=
    //{$y}&z={$z}服务器: 0,1,2,3,4 苹果端瓦片下载地址: http://mt0.google .cn/vt/lyrs=y&hl=zh-
    //htp://mt0.google.cnt
    //http://mt0.google.cn/vt/lyrs=y@883&hl=zh-CN&gl=cn&src=app&x=216483&y=100141&z=18&s=Galileo
    //谷歌卫星混合
    public static final OnlineTileSourceBase GoogleHybrid = new XYTileSource("Google-Hybrid",
            0, 19, 512, ".png", new String[]{
            "http://mt0.google.cn",
            "http://mt1.google.cn",
            "http://mt2.google.cn",
            "http://mt3.google.cn",
    }) {
        @Override
        public String getTileURLString(long pMapTileIndex) {
            Log.d("url", getBaseUrl() + "/vt/lyrs=y&scale=2&hl=zh-CN&gl=CN&src=app&x=" + MapTileIndex.getX(pMapTileIndex) + "&y=" + MapTileIndex.getY(pMapTileIndex) + "&z=" + MapTileIndex.getZoom(pMapTileIndex));
            return getBaseUrl() + "/vt/lyrs=y@883&scale=2&hl=zh-CN&gl=CN&src=app&x=" + MapTileIndex.getX(pMapTileIndex) + "&y=" + MapTileIndex.getY(pMapTileIndex) + "&z=" + MapTileIndex.getZoom(pMapTileIndex) + "&s=Galileo";
        }
    };
    //谷歌卫星
    public static final OnlineTileSourceBase GoogleSat = new XYTileSource("Google-Sat",
            0, 19, 512, ".png", new String[]{
            "http://mt0.google.cn",
            "http://mt1.google.cn",
            "http://mt2.google.cn",
            "http://mt3.google.cn",

    }) {
        @Override
        public String getTileURLString(long pMapTileIndex) {

            return getBaseUrl() + "/vt/lyrs=s&scale=2&hl=zh-CN&gl=CN&src=app&x=" + MapTileIndex.getX(pMapTileIndex) + "&y=" + MapTileIndex.getY(pMapTileIndex) + "&z=" + MapTileIndex.getZoom(pMapTileIndex);

        }
    };
    //谷歌地图
    public static final OnlineTileSourceBase GoogleRoads = new XYTileSource("Google-Roads",
            0, 18, 512, ".png", new String[]{
            "http://mt0.google.cn",
            "http://mt1.google.cn",
            "http://mt2.google.cn",
            "http://mt3.google.cn",

    }) {
        @Override
        public String getTileURLString(long pMapTileIndex) {
            return getBaseUrl() + "/vt/lyrs=m&scale=2&hl=zh-CN&gl=CN&src=app&x=" + MapTileIndex.getX(pMapTileIndex) + "&y=" + MapTileIndex.getY(pMapTileIndex) + "&z=" + MapTileIndex.getZoom(pMapTileIndex);
        }
    };
    //谷歌地形
    public static final OnlineTileSourceBase GoogleTerrain = new XYTileSource("Google-Terrain",
            0, 16, 512, ".png", new String[]{
            "http://mt0.google.cn",
            "http://mt1.google.cn",
            "http://mt2.google.cn",
            "http://mt3.google.cn",

    }) {
        @Override
        public String getTileURLString(long pMapTileIndex) {
            return getBaseUrl() + "/vt/lyrs=t&scale=2&hl=zh-CN&gl=CN&src=app&x=" + MapTileIndex.getX(pMapTileIndex) + "&y=" + MapTileIndex.getY(pMapTileIndex) + "&z=" + MapTileIndex.getZoom(pMapTileIndex);
        }
    };
    //谷歌地形带标注
    public static final OnlineTileSourceBase GoogleTerrainHybrid = new XYTileSource("Google-Terrain-Hybrid",
            0, 21, 512, ".png", new String[]{
            "http://mt0.google.cn",
            "http://mt1.google.cn",
            "http://mt2.google.cn",
            "http://mt3.google.cn",

    }) {
        @Override
        public String getTileURLString(long pMapTileIndex) {
            return getBaseUrl() + "/vt/lyrs=p&scale=2&hl=zh-CN&gl=CN&src=app&x=" + MapTileIndex.getX(pMapTileIndex) + "&y=" + MapTileIndex.getY(pMapTileIndex) + "&z=" + MapTileIndex.getZoom(pMapTileIndex);
        }
    };
    //百度地图
    //"http://online0.map.bdimg.com/tile/?qt=vtile&x={x}&y={y}&z={z}&styles=pl&scaler=1&udt=20181205&xxx={rand}";
    // return "http://online1.map.bdimg.com/onlinelabel/?qt=tile&x=" +
    //                            x + "&y=" + y + "&z=" + z +
    //                            "&styles=pl&scaler=1&udt=20191119"
    public static final OnlineTileSourceBase BaiDuMap = new XYTileSource("BaiDuMap",
            3, 18, 256, ".png", new String[]{
            "https://online1.map.bdimg.com/onlinelabel/?",
            "http://online2.map.bdimg.com/onlinelabel/?",
            "http://online3.map.bdimg.com/onlinelabel/?",
            "http://online4.map.bdimg.com/onlinelabel/?",

    }) {
        @Override
        public String getTileURLString(long pMapTileIndex) {
            LocationPoint point = GPSUtils.mercatorToBaiDumercator(new LocationPoint(MapTileIndex.getX(pMapTileIndex), MapTileIndex.getY(pMapTileIndex)));
            return getBaseUrl() + "qt=tile&x=" + (int) point.getX() + "&y=" + (int) point.getY() + "&z=" + MapTileIndex.getZoom(pMapTileIndex)+ "&styles=pl&scaler=1&udt=20191119";
        }
    };
    //高德地图
    public static final OnlineTileSourceBase AutoNaviVector = new XYTileSource("AutoNavi-Vector",
            1, 19, 256, ".png", new String[]{
            "https://wprd01.is.autonavi.com/appmaptile?",
            "https://wprd02.is.autonavi.com/appmaptile?",
            "https://wprd03.is.autonavi.com/appmaptile?",
            "https://wprd04.is.autonavi.com/appmaptile?",

    }) {
        @Override
        public String getTileURLString(long pMapTileIndex) {
            return getBaseUrl() + "x=" + MapTileIndex.getX(pMapTileIndex) + "&y=" + MapTileIndex.getY(pMapTileIndex) + "&z="
                    + MapTileIndex.getZoom(pMapTileIndex) + "&lang=zh_cn&size=1&scl=1&style=7&ltype=7";
        }
    };
    //天地图地图服务
    //影像底图 http://t0.tianditu.gov.cn/img_c/wmts?tk=您的密钥	经纬度投影
    //        http://t0.tianditu.gov.cn/img_w/wmts?tk=您的密钥	球面墨卡托投影
    public static final OnlineTileSourceBase tianDiTuImgTileSource = new XYTileSource("TianDiTuImg", 1, 18, 768, ".png",
            new String[]{
                    "http://t0.tianditu.gov.cn/DataServer?T=img_w",
                    "http://t1.tianditu.gov.cn/DataServer?T=img_w",
                    "http://t2.tianditu.gov.cn/DataServer?T=img_w",
                    "http://t3.tianditu.gov.cn/DataServer?T=img_w",
                    "http://t4.tianditu.gov.cn/DataServer?T=img_w",
                    "http://t5.tianditu.gov.cn/DataServer?T=img_w",
                    "http://t6.tianditu.gov.cn/DataServer?T=img_w"}) {
        @Override
        public String getTileURLString(final long pMapTileIndex) {
            return getBaseUrl() + "&tk=" + TIANGAN_MAP_KEY + "&x=" + MapTileIndex.getX(pMapTileIndex) + "&y=" + MapTileIndex.getY(pMapTileIndex)
                    + "&l=" + MapTileIndex.getZoom(pMapTileIndex);
        }
    };
    //天地图地图服务
    //影像注记	http://t0.tianditu.gov.cn/cia_c/wmts?tk=您的密钥	经纬度投影
    //          http://t0.tianditu.gov.cn/cia_w/wmts?tk=您的密钥	球面墨卡托投影
    //          http://t0.tianditu.gov.cn/ibo_c/wmts?tk=您的密钥
    public static final OnlineTileSourceBase tianDiTuCiaTileSource = new XYTileSource("TianDiTuCia", 1, 18, 768, ".png",
            new String[]{
                    "https://t0.tianditu.gov.cn/DataServer?T=cia_w",
                    "https://t1.tianditu.gov.cn/DataServer?T=cia_w",
                    "https://t2.tianditu.gov.cn/DataServer?T=cia_w",
                    "https://t3.tianditu.gov.cn/DataServer?T=cia_w",
                    "https://t4.tianditu.gov.cn/DataServer?T=cia_w",
                    "https://t5.tianditu.gov.cn/DataServer?T=cia_w",
                    "https://t6.tianditu.gov.cn/DataServer?T=cia_w"}) {
        @Override
        public String getTileURLString(final long pMapTileIndex) {
            return getBaseUrl() + "&tk=" + TIANGAN_MAP_KEY + "&x=" + MapTileIndex.getX(pMapTileIndex) + "&y=" + MapTileIndex.getY(pMapTileIndex)
                    + "&L=" + MapTileIndex.getZoom(pMapTileIndex);
        }
    };

    public static final String TILE_SOURCE_GOOGLE_HYBRID = "GoogleHybrid";
    public static final String TILE_SOURCE_GOOGLE_SAT = "GoogleSat";
    public static final String TILE_SOURCE_GOOGLE_ROADS = "GoogleRoads";
    public static final String TILE_SOURCE_GOOGLE_TERRAIN = "GoogleTerrain";
    public static final String TILE_SOURCE_GOOGLE_TERRAIN_HYBRID = "GoogleTerrainHybrid";
    public static final String TILE_SOURCE_AUTO_NAVI_VECTOR = "AutoNaviVector";
    public static final String TILE_SOURCE_TIAN_DITU_IMG = "tianDiTuImgTileSource";
    public static final String TILE_SOURCE_TIAN_DITU_CIA = "tianDiTuCiaTileSource";
    public static final String TILE_SOURCE_BAIDU_MAP = "BaiDuMap";
    public static final String TIANGAN_MAP_KEY = "81f3a8310bee92d3b43309908fc62d40";
    private static List<String> mTileSources;

    static {
        mTileSources = new ArrayList<>();
        mTileSources.clear();
        mTileSources.add(TILE_SOURCE_GOOGLE_HYBRID);
        mTileSources.add(TILE_SOURCE_GOOGLE_SAT);
        mTileSources.add(TILE_SOURCE_GOOGLE_ROADS);
        mTileSources.add(TILE_SOURCE_GOOGLE_TERRAIN);
        mTileSources.add(TILE_SOURCE_GOOGLE_TERRAIN_HYBRID);
        mTileSources.add(TILE_SOURCE_AUTO_NAVI_VECTOR);
        mTileSources.add(TILE_SOURCE_TIAN_DITU_IMG);
        mTileSources.add(TILE_SOURCE_TIAN_DITU_CIA);
        mTileSources.add(TILE_SOURCE_BAIDU_MAP);
    }

    /**
     * 通过名称返回OnlineTileSourceBase
     *
     * @param name 名称
     * @return OnlineTileSourceBase
     */
    public static OnlineTileSourceBase getOnlineTileSourceBaseByName(String name) {
        if (TextUtils.isEmpty(name))
            return null;
        switch (name) {
            //谷歌卫星混合
            case TILE_SOURCE_GOOGLE_HYBRID:
                return GoogleHybrid;
            //谷歌卫星
            case TILE_SOURCE_GOOGLE_SAT:
                return GoogleSat;
            //谷歌地图
            case TILE_SOURCE_GOOGLE_ROADS:
                return GoogleRoads;
            //谷歌地形
            case TILE_SOURCE_GOOGLE_TERRAIN:
                return GoogleTerrain;
            //谷歌地形带标注
            case TILE_SOURCE_GOOGLE_TERRAIN_HYBRID:
                return GoogleTerrainHybrid;
            //高德地图
            case TILE_SOURCE_AUTO_NAVI_VECTOR:
                return AutoNaviVector;
            //影像地图 _W是墨卡托投影  _c是国家2000的坐标系
            case TILE_SOURCE_TIAN_DITU_IMG:
                return tianDiTuImgTileSource;
            //影像标注 _W是墨卡托投影  _c是国家2000的坐标系
            case TILE_SOURCE_TIAN_DITU_CIA:
                return tianDiTuCiaTileSource;
            case TILE_SOURCE_BAIDU_MAP:
                return BaiDuMap;
        }
        return null;
    }

    public static List<String> getmTileSources() {
        return mTileSources;
    }


    /**
     * 加载离线地图
     */
    public static File mapViewOtherData(String path) {
        String strFilepath = Environment.getExternalStorageDirectory().getPath() + path;
        File exitFile = new File(strFilepath);
        String fileName = exitFile.getName();

        fileName = fileName.substring(fileName.lastIndexOf(".") + 1);
        if (ArchiveFileFactory.isFileExtensionRegistered(fileName)) {
            try {
                return exitFile;

//                    String source = "";
//                    IArchiveFile[] archives = tileProvider.getArchives();
//                    if (archives.length > 0) {
//                        Set<String> tileSources = archives[0].getTileSources();
//                        if (!tileSources.isEmpty()) {
//                            source = tileSources.iterator().next();
//                            mMapView.setTileSource(FileBasedTileSource.getSource(source));
//                        } else {
//                            mMapView.setTileSource(Objects.requireNonNull(GoogleTileSource.AutoNaviVector));
//                        }
//
//                    } else
//                        mMapView.setTileSource(Objects.requireNonNull(GoogleTileSource.AutoNaviVector));
//                    ToastUtils.showShort("Using " + exitFile.getAbsolutePath() + " " + source);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            ToastUtils.showShort(" did not have any files I can open! Try using MOBAC");
        } else {
            ToastUtils.showShort(" dir not found!");
        }
        return null;
    }


//        //判断已存在点中是否有在十米之内的点
//        for (int j = 0; j < geoPointList.size(); j++) {
//            if (MapUtils.distance(geoPointList.get(j).getLatitude(),geoPointList.get(j).getLongitude(),geoPoint.getLatitude(),geoPoint.getLongitude())< MIN_ADD_MARKER_DISTANCE){
//                ToastUtils.showShort("此处已有点");
//                return;
//            }
//        }

}
